package com.mall.file.controller;

import com.mall.file.file.FileHandler;
import com.mall.common.util.RespResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Darren
 * @date 2022-07-29 17:44
 * Description：
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FileHandler fileHandler;

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public RespResult upload(MultipartFile file) throws IOException {
        fileHandler.upload(file.getOriginalFilename(), file.getBytes());
        return RespResult.ok();
    }

    /**
     * 文件下载
     *
     * @param filename
     * @return
     */
    @GetMapping("/download/{filename}")
    public void download(HttpServletResponse response, @PathVariable("filename") String filename) throws IOException {
        byte[] bytes = fileHandler.download(filename);
        ServletOutputStream os = response.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }
}
